<?php

namespace Drupal\shusy_product_s_cost\Entity;

use Entity;

class ShusyProductSCost extends Entity {

  public $id;

  public $vid;

  public $uid;

  public $op_uid;

  public $created;

  public $changed;

  public $is_new_revision;

  public $product_id = 0;

  public $cost_type = 'weight';

  function __construct($values = []) {
    $this->is_new_revision = TRUE;
    parent::__construct($values, 'shusy_product_s_cost');
  }

  public function save() {
    $this->changed = REQUEST_TIME;
    if (empty($this->created)) {
      $this->created = REQUEST_TIME;
    }

    $this->op_uid = $GLOBALS['user']->uid;
    if (empty($this->uid)) {
      $this->uid = $GLOBALS['user']->uid;
    }

    return parent::save();
  }

  /**
   * @param int $qty 购买的数量
   *
   * @return int
   */
  function getAmount(int $qty) {
    $amount = $this->getNearItem($qty);
    return $amount * $qty;
  }

  /**
   * @param int $qty
   *
   * @return int
   */
  protected function getNearItem(int $qty) {
    $amount = 0;
    $items = shusy_product_s_cost_item_load_multiple(FALSE, [
      'product_s_cost_id' => $this->id,
      'status' => 1,
    ]);
    $tmps = [];
    foreach ($items as $item) {
      if ($item instanceof ShusyProductSCostItem) {
        if ($qty >= $item->number) {
          $tmps[] = [
            'amount' => ceil($item->amount / $item->number),
            'weight' => $item->weight - $item->number,
          ];
        }
      }
    }
    usort($tmps, 'drupal_sort_weight');
    if (!empty($tmps)) {
      $item = array_shift($tmps);
      $amount = $item['amount'];
    }
    return $amount;
  }
}
